package com.freecloud.javabasics.network.socket.demo1;

import com.freecloud.common.LoggerUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * socket服务端
 * @Author: maomao
 * @Date: 2020-03-15 11:20
 */
public class ServerSocketDemo1 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //服务端一定需要监听一个端口号，Ip默认使用本机IP地址
            serverSocket = new ServerSocket(8080);
            LoggerUtil.println("服务端-2" );
            //接收客户端的连接（阻塞）
            Socket socket = serverSocket.accept();
            LoggerUtil.println("服务端-1" );
            //拿到网络输入流
            BufferedReader in = getInputStream( socket);
            //拿到网络输出流
            PrintWriter printWriter = getOutputStream(socket);

            LoggerUtil.println("服务端1" );
            //拿到控制台输入流
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
            LoggerUtil.println("服务端2" );
            String clentMsg = in.readLine();
            LoggerUtil.println("服务端3" );
            LoggerUtil.println("服务端接收到clent端信息：" + clentMsg);

            String sysMsg = sin.readLine();
            while (!clentMsg.equals("bye")){
                //获得客户端输入信息
                LoggerUtil.println("接收到客户端信息：" + in.readLine());
                //将控制台内容，发送到客户端
                printWriter.println(sysMsg);
                printWriter.flush();
                //重新读取控制台信息
                sysMsg = sin.readLine();
                clentMsg = in.readLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static PrintWriter getOutputStream(Socket socket) throws IOException {
        return new PrintWriter(socket.getOutputStream());
    }

    public static BufferedReader getInputStream(Socket socket) throws IOException {
        //拿到输入流
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
}
